/* eslint-disable */
/*
 * @Author: FTT
 * @Date: 2022-03-07 18:09:11
 * @LastEditors: FTT
 * @LastEditTime: 2022-05-24 16:23:41
 */
// /src/pages/editor/index.tsx
import React, { useEffect } from 'react';
import { connect } from 'react-redux';
import { HTML5Backend } from 'react-dnd-html5-backend';
import { DndProvider } from 'react-dnd';
import { isEmpty } from 'lodash';
import moment from 'moment';
import { fetchTree, appendCom } from '@/app/codeTreeSlice';
import { useAppSelector } from '@/app/hooks';
import { useAsyncFn } from 'react-use';
import store from '@/app/store';
import { get } from '@/utils/request';
import { getWebRootNew } from '@/utils/utils';
import { formatDate } from '@/utils/date';
import { savePageState } from '@/app/newPageSlice';
import { CONTAINER_LIST, LOCAL_TEST_COMPONENTS } from '@/constants/constants';
import layoutFields from '@/components/editor/schema/fields/thirdComponents';
import Left from '@/components/editor/Left';
import Header from '@/components/Layout/Header';
import Right from '@/components/editor/Right';
import Canvas from '@/components/editor/Canvas';
// import ResizableContainer from '@/components/ResizableContainer';
import Floor from '@/components/editor/Floor';

import styles from './index.less';

const mergeLocalComponents = (originList: any[] = []) => {
  const cloned = originList.map((group: any) => ({
    ...group,
    subGroupList: (group?.subGroupList || []).map((sub: any) => ({
      ...sub,
      componentList: [...(sub?.componentList || [])],
    })),
  }));

  LOCAL_TEST_COMPONENTS.forEach((localGroup) => {
    const targetGroup = cloned.find(
      (group) =>
        group?.groupCode === localGroup.groupCode || group?.groupName === localGroup.groupName,
    );

    if (targetGroup) {
      targetGroup.subGroupList = targetGroup.subGroupList || [];
      localGroup.subGroupList?.forEach((localSub) => {
        const matchedSub = targetGroup.subGroupList.find(
          (sub: any) => sub?.groupName === localSub.groupName,
        );

        if (matchedSub) {
          const existCodes = new Set(
            (matchedSub.componentList || []).map((comp: any) => comp?.componentCode),
          );
          matchedSub.componentList = matchedSub.componentList || [];
          localSub.componentList?.forEach((comp) => {
            if (!existCodes.has(comp.componentCode)) {
              matchedSub.componentList = [...matchedSub.componentList, comp];
              existCodes.add(comp.componentCode);
            }
          });
        } else {
          targetGroup.subGroupList = [
            ...targetGroup.subGroupList,
            {
              ...localSub,
              componentList: [...(localSub.componentList || [])],
            },
          ];
        }
      });
    } else {
      cloned.push({
        ...localGroup,
        subGroupList: (localGroup.subGroupList || []).map((sub) => ({
          ...sub,
          componentList: [...(sub.componentList || [])],
        })),
      });
    }
  });

  return cloned;
};

function Editor(props: any) {
  const verState = useAppSelector((state) => state.newPageInfo);
  const { codeTree, location } = props;

  // 查询组件
  const [, doQueryCom] = useAsyncFn(async (params: any) => {
    const res: any = await get({
      url: `${getWebRootNew()}/appops/cms/component-library/components-with-group`,
      params,
    });
    return res.data;
  }, []);
  // 根据路由参数判断外部跳转 /editor?fromPageBuilderJson=true&pageCode=test TODO联调
  const { fromPageBuilderJson, pageCode } = location?.query || {};
  const fromPageBuilderJsonFlag = `${fromPageBuilderJson}` === 'true';

  const upstateCanvas = async () => {
    try {
      const pageDetail = verState?.pageVerI18nDetail || {};
      const pageType = verState?.pageVerInfoDetail?.pageType || pageDetail?.pageType || '';
      const verPageCompositionList =
        (pageType === '2' ? pageDetail?.containerList : pageDetail?.pageCompositionList) || [];
      const verContent = JSON.parse((pageDetail?.content || '').replace(/\n/g, '\\\\n') || null);
      // 此时要将pageDetail.pageCompositionList值塞进content中
      // 1.将本地的pageCompositionList和content取出
      const verChildren = verContent?.children || [];

      const verNewArr: any = [];
      if (!fromPageBuilderJsonFlag) {
        verPageCompositionList.map((item: any, index: number) => {
          const { effDate, expDate } = item;
          verNewArr[index] = {
            effDate: formatDate(effDate, 'YYYYMMDDhhmmss', 'MM/DD/YYYY HH:mm:ss'),
            expDate: formatDate(expDate, 'YYYYMMDDhhmmss', 'MM/DD/YYYY HH:mm:ss'),
          };
          return item;
        });
      }
      // 构建数组的渲染时间为具体日期，type固定为
      const newVerChildren = verChildren.map((item: any, index: number) => {
        const { props, type } = item;
        const { expireType, expireTimeFormat, publishType, publishTimeFormat } = props || {};
        return {
          ...item,
          props: {
            ...props,
            expireTime:
              verNewArr[index]?.expDate && !fromPageBuilderJsonFlag
                ? moment(verNewArr[index].expDate, 'MM/DD/YYYY HH:mm:ss')
                : undefined,
            expireType: type === 'CountdownPost' || type === 'DITOCountdownPost' ? expireType : undefined,
            expireTimeFormat: type === 'CountdownPost' || type === 'DITOCountdownPost' ? expireTimeFormat : 'AI',
            publishTime:
              verNewArr[index]?.effDate && !fromPageBuilderJsonFlag
                ? moment(verNewArr[index].effDate, 'MM/DD/YYYY HH:mm:ss')
                : undefined,
            publishType: type === 'CountdownPost' || type === 'DITOCountdownPost' ? publishType : undefined,
            publishTimeFormat: type === 'CountdownPost' || type === 'DITOCountdownPost' ? publishTimeFormat : 'AI',
          },
        };
      });
      // 塞回content
      let newContent = null;
      if (newVerChildren.length > 0) {
        newContent = JSON.stringify({
          ...verContent,
          children: newVerChildren,
        });
      }
      const newCodeTree = newContent ? JSON.parse(newContent) : null;
      // const newCodeTree = JSON.parse(pageDetail.content || null);
      if (newCodeTree) {
        store.dispatch(
          fetchTree({
            ...newCodeTree,
          }),
        );
      }
    } catch (err) {
      console.log(err);
    }
  };
  const handleResData = (resData) => {
    const { pageType, appCodes } = resData || {};
    const pageContent = JSON.parse(resData?.content || '{}') || { children: [] }; // pageVer的content
    const children =
      pageContent.children && pageContent.children.length
        ? pageContent.children.map((item: any) => {
            const { props, type } = item;
            return {
              ...item,
              props: {
                ...props,
                expireTimeFormat: '',
                expireTime: props?.expDate,
                expireType: type === 'CountdownPost' ? props?.expireType : undefined,
                publishTimeFormat: '',
                publishTime: props?.effDate,
                publishType: undefined,
              },
            };
          })
        : undefined;
    const content = JSON.stringify({
      ...pageContent,
      children,
    });
    if (pageType === '2') {
      if (isEmpty(resData?.content)) {
        // H5空数据时，默认添加容器
        const layoutObj = layoutFields.find((n: any) => n.type === 'Layout' && n.props.containerType === 'Layout1');
        store.dispatch(
          appendCom({
            hoverParentId: 'root',
            hoverIndex: '',
            data: {},
            item: layoutObj,
            positionDown: true,
          }),
        );
      }
    }
    store.dispatch(
      savePageState({
        // pageVerI18nDetail: { ...newData, pageCompositionList: newCom, content: JSON.stringify(newContent) },
        pageVerI18nDetail: resData,
        pageVerInfoDetail: {...resData,appCode:resData?.appCodes},
        currentStep: 0,
        currDeviceType: 'app',
      }),
    );
  };
  const qryComList = async () => {
    const pageBuilderJsonList = localStorage.getItem('pageBuilderJsonList') || [];
    let pageType = '3'; // Default page type for LOCAL_TEST_COMPONENTS (H5 components)
    let appCodes;

    if (fromPageBuilderJsonFlag && pageCode) {
      const resData = (pageBuilderJsonList || []).find((it) => it.pageCode === pageCode) || {};
      pageType = resData?.pageType || '3';
      appCodes = resData?.appCodes;
      handleResData(resData);
    }

    const params = {
      componentTypes: pageType,
    };
    if (appCodes) {
      params.appCodes = appCodes;
    }
    const comRes = await doQueryCom(params);
    // if (comRes && comRes?.code === '200') {
    const result: any = [];
    const allComList = comRes?.data || [];
    // const allComList = mockData;
    const mergedComList = mergeLocalComponents([...CONTAINER_LIST, ...allComList]);
    const currComList = mergedComList.map((item: any) => ({
      firstCatg: item?.groupName,
      thumbnail: item?.thumbnail,
      groupId: item?.groupId,
      groupCode: item?.groupCode,
      children: (item?.subGroupList || []).map((key: any) => ({
        parType: key?.groupName,
        thumbnail: key?.thumbnail,
        lastChildren: (key?.componentList || []).map((com: any) => {
          const res = {
            type: com?.componentCode,
            containerType: com?.containerType,
            name: com?.componentName,
            applyPageTypes: pageType,
            componentCode: com?.componentCode,
            componentType: com?.componentType,
            componentPreview: com?.componentPreview,
            codeExtractedPath: com?.codeExtractedPath,
            componentVerSeq: com?.componentVerSeq,
            componentIcon: com?.componentIcon,
            componentVerId: com?.componentVerId,
            propertiesSource: com?.propertiesSource,
            stylesSource: com?.stylesSource,
            propertyList: com?.propertyList || [],
            totalNum: 999,
          };
          if (!com?.codeExtractedPath && com?.propertiesSource === '2' && com?.stylesSource === '2') {
            res.totalNum === 999;
          }
          return res;
        }),
      })),
    }));

    (currComList || []).forEach((category: any) => {
      category.children.forEach((child: any) => {
        child.lastChildren.forEach((item: any) => {
          if (item.codeExtractedPath) {
            result.push(item);
          }
        });
      });
    });
    store.dispatch(
      savePageState({
        componentsList: currComList,
      }),
    );
  };
  useEffect(() => {
    if (!isEmpty(verState?.pageVerI18nDetail)) {
      upstateCanvas();
    }
  }, [JSON.stringify(verState?.pageVerI18nDetail)]);
  useEffect(() => {
    // Always load component list to show LOCAL_TEST_COMPONENTS
    qryComList();
  }, []);

  return (
    <DndProvider backend={HTML5Backend}>
      <div className={styles.layoutBox}>
        <Header detail={verState?.pageVerI18nDetail || {}} />
        <div className={styles.mainContentBox}>
          <Left />
          <Canvas />
          {!isEmpty(codeTree?.children) && (
            <>
              <Floor />
              <Right />
            </>
          )}
        </div>
      </div>
    </DndProvider>
  );
}

export default connect((state: any) => {
  return {
    codeTree: state.codeTree,
  };
})(Editor);
